package com.led.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.led.datas.DataAccess;
import com.led.datas.DatasBasicAccess;
import com.led.datas.UserAccess;
import com.led.datatype.DataBasic;
import com.led.datatype.LedData;
import com.led.datatype.ServletResult;
import com.led.datatype.UserInfo;

/**
 * Servlet implementation class GetDatas
 */
public class DataServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static String OPTYPES_INSERT = "insert";
	public static String OPTYPES_DELETE = "delete";
	public static String OPTYPES_GETBASIC = "getBasic";
	public static String OPTYPES_GETREAL = "getReal";
	public static String OPTYPES_GETALL = "getAll";
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DataServlet() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	//
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
//		String token=request.getParameter("token");
//		String dataId = request.getParameter("dataId");
		ServletResult returnResouce = null;
		
		String opType = request.getParameter("opType");
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		
		if(null == userName || userName.length() == 0 ||
		   null == password || password.length() == 0){
			System.out.println("userName:" + userName + ", password:" + password 
					+ "is not set, check session");
			if(null != request.getSession().getAttribute("userName") &&
			   null != request.getSession().getAttribute("password")){
				userName = (String) request.getSession().getAttribute("userName");
				password = (String) request.getSession().getAttribute("password");
				System.out.println("session has userName:" + userName);
			} else {
				System.out.println("session hasn't userName, set to public");
				userName = "public";
				password = "public";
			}
		} else {
			request.getSession().setAttribute("userName", userName);
			request.getSession().setAttribute("password", password);
		}
		if(null == opType || opType.length() == 0){
			opType = OPTYPES_GETALL;
		}
		
		UserInfo userInfo = UserAccess.getUserInfoByNamePassword(userName, password);

		int needSeeOthers = 1;
		try{
			needSeeOthers = 1 - Integer.parseInt(request.getParameter("noNeedSeeOthers"));
			System.out.println("request no see noNeedSeeOthers:" +  request.getParameter("noNeedSeeOthers") + ", ok");
			userInfo.setCanSeeOthers(needSeeOthers); //default is 1, user can change by request
		}catch(Exception e){
		}
		if(!isPermissionAllow(userInfo, opType)){
			System.out.println("permission is deny for user:" + userName + ", opType:" + opType);
			returnResouce = new ServletResult(-1, "permission is deny for user:" + userName + ", opType:" + opType);
		} else if(OPTYPES_INSERT.equalsIgnoreCase(opType)){
			String info = request.getParameter("info");
			String dataReal = request.getParameter("dataReal");
			if(null == info || info.length() == 0){
				System.out.println("info is null when in insert datas");
				returnResouce = new ServletResult(-1, "info or jsData all not set!!");
			} else if(null == dataReal || dataReal.length() == 0){
				System.out.println("dataReal is null when in insert datas");
				returnResouce = new ServletResult(-1, "dataReal or jsData all not set!!");
			} else {
				LedData data = new LedData(info, dataReal, userInfo.getId());
				boolean ret = DataAccess.saveToDB(data);
				if(ret){
					returnResouce = new ServletResult("update to Server succes!");
				} else {
					returnResouce = new ServletResult(-1, "update to Server failed!");
				}
			}
		} else if(OPTYPES_DELETE.equals(opType)){
			//only can delete self
			String realDataIdx = request.getParameter("id");
			int idDataReal = Integer.parseInt(realDataIdx);
			DataBasic databasic = DatasBasicAccess.getDatasBasicByIdxDatas(idDataReal);
			if(null == databasic){
				System.out.println("no realIdx for id:" + idDataReal + ", user:" + userInfo.getName());
				returnResouce = new ServletResult(-2, "no datas for realIdx:" + idDataReal + ", user:" + userInfo.getName());
			} else {
				if(!userName.equals(databasic.getUserName())){
					System.out.println("realIdx for id:" + idDataReal + " exist,"
							+ " but need user:" + databasic.getUserName() + " currentUser:" + databasic.getUserName());
					returnResouce = new ServletResult(-2,"realIdx id:" + idDataReal + " is not current user:" + userName + ", needUser:" + databasic.getUserName());
				} else {
					System.out.println("user:" + userName + " is to remove realdatas, idxReal:" + idDataReal);
					if(!DataAccess.removeDataByIDRealData(idDataReal)){
						System.out.println("user:" + userName + " remove idxReal:" + idDataReal + " failed");
						returnResouce = new ServletResult(-2, "user:" + userName + " remove idxReal:" + idDataReal + " failed, db error!" );
					} else {
						returnResouce = new ServletResult("remove idxReal:" + idDataReal + " Success!" );
					}
				}
			}
//			DataAccess.getDatasBasic(userInfo)
			
		} else if(OPTYPES_GETBASIC.equalsIgnoreCase(opType)){
			String datas = DatasBasicAccess.getDatasBasic(userInfo);
			returnResouce = new ServletResult(datas);

		} else if(OPTYPES_GETREAL.equalsIgnoreCase(opType)){
			String str_idxReal = request.getParameter("id");
			if(null == str_idxReal || str_idxReal.length() == 0){
				returnResouce = new ServletResult(-1, "no id set for getReal!");
			} else {
				try{
					int id = Integer.parseInt(str_idxReal);
					String datas = DataAccess.getDatasReal(id);
					returnResouce = new ServletResult(datas);
				} catch(Exception e) {
					returnResouce = new ServletResult(-1, "err datas for getReal,id:" + str_idxReal + ")");
				}
			}
		} else {
			String datas = DataAccess.getAllDatas(userInfo);
			returnResouce = new ServletResult(datas);
		}

		if(null != returnResouce){
			PrintWriter pw = response.getWriter();
			System.out.println("ret:" + returnResouce.toString());
			pw.write(returnResouce.toString());
			pw.flush();
			pw.close();
		}
	}
	
	boolean isPermissionAllow(UserInfo userInfo, String opType){
		if(null == userInfo){
			System.out.println("user is not exist!");
			return false;
		}
		if(OPTYPES_GETBASIC.equals(opType) ||
		   OPTYPES_GETREAL.equals(opType) ||
		   OPTYPES_GETALL.equals(opType)){
			return 1 == userInfo.getCanQuery();
			
		} else if(OPTYPES_INSERT.equals(opType)||
				OPTYPES_DELETE.equals(opType)){
			return 1 == userInfo.getCanModify();

		} else {
			System.out.println("opType:" + opType + " is not support!");
			return false;
		}
	}
	

}
